package com.ruoyi.web.controller.shopping.backend;

import com.ruoyi.system.view.common.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/backend/shopping/common")
public class CommonBackendController {

    @Value("${backend.shopping.path}")
    private String basePath;


    @GetMapping
    public void test(){
        System.out.println(1);
    }

    /*文件上传*/
    @PostMapping("/upload")
    public Result<String> upload(MultipartFile file){
        String originalFilename = file.getOriginalFilename();
        //生产uuid然后拼接后缀名
        originalFilename = UUID.randomUUID()+originalFilename.substring(originalFilename.lastIndexOf("."));

        File dir = new File(basePath);
        if (!dir.exists()) {
            //目录不存在 创建文件
            dir.mkdir();
        }
        try {
            file.transferTo(new File(basePath+originalFilename));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Result.success("/profile/"+originalFilename,"上传成功");
    }

    /*文件下载*/
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){
        try {
            FileInputStream is = new FileInputStream(new File(basePath+name));
            response.setContentType("image/jpeg");
            int len = 0;
            byte[] bytes = new byte[1024];
            ServletOutputStream os = response.getOutputStream();
            while ((len=is.read(bytes)) != -1){
                os.write(bytes,0,len);
                os.flush();
            }
            is.close();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}